﻿using AutoMapper;
using Dapper;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Drawing.Charts;
using DocumentFormat.OpenXml.InkML;
using DocumentFormat.OpenXml.Office2013.Drawing.Chart;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Wordprocessing;
using Hangfire;
using housingsafety.server.Caching.Core;
using housingsafety.server.Entities;
using housingsafety.server.Entities.DataModels;
using housingsafety.server.Helpers;
using housingsafety.server.Models;
using housingsafety.server.Repository;
using housingsafety.server.Repository.Extensions;
using housingsafety.server.Svcs;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Npgsql;
using Npoi.Mapper;
using NPOI.HPSF;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Asn1.Ocsp;
using Org.BouncyCastle.Ocsp;
using Quartz.Util;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Drawing.Drawing2D;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static housingsafety.server.Controllers.HouseMngCheckOutController;
using static housingsafety.server.Controllers.HouseMngController;
using static housingsafety.server.Controllers.HouseMngSqjzHouseController;
using static housingsafety.server.Controllers.SampleTaskController;
using static housingsafety.server.Models.HelperModel;

namespace housingsafety.server.Controllers
{
    /// <summary>
    /// 大屏基本信息 展示
    /// </summary>
    public class HouseMngCheckOutController : BaseController<HouseMngCheckController>
    {
        private readonly IUserTokenService _userService;
        private readonly TokenManagement _tokenManagement;
        public IConfiguration Configuration { get; }
        private readonly IRepository<ZmVillageFireSafety> _villageFireSafetyRepository;
        private readonly ICache _cache;
        private readonly IMapper _mapper;
        private readonly IStorageProvider _storageProvider;
        private readonly ZmDbContext _dbContext;
        private readonly IRepository<ZmUser> _userRepository;
        private readonly IRepository<ZmBuildings> _buildingsRepository;
        private readonly IRepository<ZmBuildingsLayer> _buildingsLayerRepository;
        private readonly IRepository<ZmUpdateLog> _zmupdateRepository;
        private readonly IRepository<ZmUpdateLog> _zmupdate;
        private readonly IRepository<ZmFileAttach> _fileAttachRepository;
        private readonly IRepository<ZmPlaceCommercial> _placeCommercialRepository;
        private readonly IRepository<ZmPlaceResident> _placeResidentRepository;
        private readonly IOptions<StaticDataConf> _staticVtOptions;
        private readonly IRepository<ZmDepartment> _departmentRepository;
        private readonly IRepository<RiskCensusHouseYhpc> _riskHouseRepository;
        private readonly IRepository<RiskCensusYhpcUpldFile> _riskHouseFileRepository;
        private readonly IRepository<ZmPlaceResidentCheck> _placeResidentCheckRepository;
        private readonly IRepository<ZmPlaceCommercialCheck> _placeCommercialCheckRepository;
        private readonly IRepository<ZmYtPhoto> _zmYtPhotoRepository;
        private readonly IDbTransaction _transaction;

        private readonly Microsoft.AspNetCore.Http.Features.FormOptions _defaultFormOptions = new Microsoft.AspNetCore.Http.Features.FormOptions();
        private readonly string[] _permittedExtensions = { ".mp3", ".mp4", ".jpg", ".jpeg", ".png", ".geojson", ".doc", ".docx" };

        private static object _lock = new object();

        public HouseMngCheckOutController(IOptions<TokenManagement> tokenManagement, IUserTokenService userService, IStorageProvider storageProvider
            , IRepository<ZmDepartment> departmentRepository
            , IRepository<ZmUser> userRepository
              , IRepository<ZmVillageFireSafety> villageFireSafetyRepository
              , IRepository<ZmBuildings> buildingsRepository
            , IRepository<ZmBuildingsLayer> buildingsLayerRepository
            , IRepository<ZmFileAttach> fileAttachRepository
            , IRepository<ZmPlaceCommercial> placeCommercialRepository
            , IRepository<ZmPlaceResident> placeResidentRepository
            , IRepository<RiskCensusHouseYhpc> riskHouseRepository
            , IRepository<RiskCensusYhpcUpldFile> riskHouseFileRepository
            , IRepository<ZmPlaceResidentCheck> placeResidentCheckRepository
            , IRepository<ZmPlaceCommercialCheck> placeCommercialCheckRepository
            , IRepository<ZmYtPhoto> zmYtPhotoRepository
            , IMapper mapper, ICacheProvider cacheProvider, ZmDbContext dbContext
            , IOptions<StaticDataConf> staticVtOptions
            , ILogger<HouseMngCheckController> logger,
            IConfiguration configuration
            , IRepository<ZmSystemLog> systemLogRepository, IRepository<ZmUpdateLog> zmupdateRepository) : base(logger, systemLogRepository)
        {
            _tokenManagement = tokenManagement.Value;
            _userService = userService;
            _zmupdateRepository = zmupdateRepository;
            _storageProvider = storageProvider;
            _mapper = mapper;
            _dbContext = dbContext;
            _cache = cacheProvider.CreateCache();
            _zmYtPhotoRepository = zmYtPhotoRepository;
            _userRepository = userRepository;
            _buildingsRepository = buildingsRepository;
            _buildingsLayerRepository = buildingsLayerRepository;
            _fileAttachRepository = fileAttachRepository;
            _placeCommercialRepository = placeCommercialRepository;
            _placeResidentRepository = placeResidentRepository;
            _staticVtOptions = staticVtOptions;
            _departmentRepository = departmentRepository;
            _riskHouseRepository = riskHouseRepository;
            _riskHouseFileRepository = riskHouseFileRepository;
            _placeResidentCheckRepository = placeResidentCheckRepository;
            _placeCommercialCheckRepository = placeCommercialCheckRepository;
            Configuration = configuration;
            _villageFireSafetyRepository = villageFireSafetyRepository;
            _zmupdateRepository = zmupdateRepository;

        }

        List<string> stringList = new List<string> { "栋", "栋", "处", "处" };



        /// <summary>
        /// 某栋房屋的检查、自查记录
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("/api/v1/nologin/village/baseInfo/baseInfoDetaile")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<Page<object>> baseInfoDetaile([FromQuery] string fwbh, [FromQuery] int pageIndex, [FromQuery] int limit)
        {
            if (pageIndex < 0)
            {
                return new RespRet<Page<object>>(false, "PageIndex must >= 0");
            }
            string strWhere = "";
            string sql = @"select  ROW_NUMBER() OVER ()index ,*   from ( select b1.*,COALESCE(yhnum,0) yhnum,case when yhnum is null then '已检查无隐患' else  '已检查有隐患' end yhzt,COALESCE(zgnum,0) zgnum, case when fwzt is null then '正常出租' else case when fwzt=1 then '不出租' else  '已拆除' end end fwztname,
                         case when zgnum is null then '/' else case when zgnum=0 then '未整改' else  '已整改' end end zgzt,'详情' cz  from (select t2.hzxm,t2.address,t1.fwbh,t1.yhlog_id, t1.id,to_char(t1.create_on::timestamp(0) without time zone, 'YYYY-MM-DD HH24:MI:SS') pcsj ,t1.create_name ,fwzt
                           from (select m1.*,m2.id yhlog_id from zm_pc_baselog_cj m1, zm_pc_yhlog_cj m2 where m1.id=m2.base_id) t1,zm_buildings t2 where t1.fwbh=t2.fwbh ) b1 left join 
                           (select count(fwbh) yhnum, yhlog_id, sum(case when zg_value= '1' then 1 else 0 end) zgnum from zm_pc_yhlog_dx_cj 
                           group by yhlog_id) b2 on b1.yhlog_id = b2.yhlog_id  order by pcsj desc)  t   
                       where fwbh='" + fwbh + "' " + strWhere + "   limit " + limit + " offset " + limit * (pageIndex - 1);
            if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
         || sql.Contains("delete from", StringComparison.OrdinalIgnoreCase)
         || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<Page<object>>(false, "不符合规范，禁止执行");
            }
            string sql_count = @"select  count(1) cnt  from ( select b1.*,COALESCE(yhnum,0) yhnum,case when yhnum is null then '已检查无隐患' else  '已检查有隐患' end yhzt,COALESCE(zgnum,0) zgnum, case when fwzt is null then '正常出租' else case when fwzt=1 then '不出租' else  '已拆除' end end fwztname,
                         case when zgnum is null then '/' else case when zgnum=0 then '未整改' else  '已整改' end end zgzt,'详情' cz  from (select t2.hzxm,t2.address,t1.fwbh,t1.yhlog_id,t1.id,to_char(t1.create_on::timestamp(0) without time zone, 'YYYY-MM-DD HH24:MI:SS') pcsj  ,t1.create_name ,fwzt
                           from (select m1.*,m2.id yhlog_id from zm_pc_baselog_cj m1, zm_pc_yhlog_cj m2 where m1.id=m2.base_id) t1,zm_buildings t2 where t1.fwbh=t2.fwbh ) b1 left join 
                           (select count(fwbh) yhnum, yhlog_id, sum(case when zg_value= '1' then 1 else 0 end) zgnum from zm_pc_yhlog_dx_cj 
                           group by yhlog_id) b2 on b1.yhlog_id = b2.yhlog_id order by pcsj desc)  t    where fwbh='" + fwbh + "'" + strWhere;

            if (sql_count.Contains("insert into", StringComparison.OrdinalIgnoreCase)
          || sql_count.Contains("delete from", StringComparison.OrdinalIgnoreCase)
          || sql_count.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<Page<object>>(false, "不符合规范，禁止执行");
            }
            //执行语句
            var list = _dbContext.Database.GetDbConnection().Query<object>(sql).ToList();
            int count = _dbContext.Database.GetDbConnection().QueryFirstOrDefault<int>(sql_count);

            return new RespRet<Page<object>>(true, "ok", new Page<object> { Items = list, NextPageIndex = pageIndex, PageTotal = count, Total = count });
        }


        /// <summary>
        /// 获取当前房屋的检查记录中的详细信息
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("/api/v1/nologin/village/{id}/restinfo/")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<HourseBaseInfo>), 200)]
        public RespRet<object> restinfo2([FromRoute] string id)
        {
            try
            {
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@"select *    FROM zm_pc_baselog_cj    ");
                sbSqlWhere.Append($@" id = @fwbh and");
                sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));
                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                var ZmPcBasecj = _dbContext.ZmPcBaseLogCj.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (ZmPcBasecj == null)
                {
                    return new RespRet<object>(false, "未找到检查记录");
                }
                var from = _dbContext.ZmPcYhLogCj.FirstOrDefault(c => c.BaseId == id);
                if (from != null)
                {
                    from.UseElectricBicyclePhoto = from.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicyclePhoto));
                    from.UseBottledLiquefiedGasPhoto = from.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasPhoto));
                    from.UseStackedItemsPhoto = from.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsPhoto));
                    from.SlljdxPhoto = from.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxPhoto));
                    from.YgbjwfwhyxPhoto = from.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxPhoto));
                    from.MhqwbcwhyxPhoto = from.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxPhoto));
                    from.JyplmhxtwbcwhyxPhoto = from.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxPhoto));
                    from.UseElectricBicycleZgPhoto = from.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicycleZgPhoto));
                    from.UseBottledLiquefiedGasZgPhoto = from.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasZgPhoto));
                    from.UseStackedItemsZgPhoto = from.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsZgPhoto));
                    from.SlljdxZgPhoto = from.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxZgPhoto));
                    from.YgbjwfwhyxMsgZgPhoto = from.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxMsgZgPhoto));
                    from.MhqwbcwhyxZgPhoto = from.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxZgPhoto));
                    from.JyplmhxtwbcwhyxZgPhoto = from.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxZgPhoto));
                }

                var ZmPcBaseDto = _mapper.Map<ZmPcBaseLogCjDto>(ZmPcBasecj);
                var ZmPcYhDto = _mapper.Map<ZmPcYhLogCjDto2>(from);

                var r = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBaseDto, ZmPcYh = ZmPcYhDto });
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }




        /// <summary>
        /// 防火委平台接口  接口中提供自建房总数、周自查率、人员疏散通道已达标数、未达标数、达标率
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [HttpPost("houses/GetZcData")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]

        public RespRet<object> GetZcData([FromBody] DateQuery param)
        {
            var usernNumber = this.CurrentUser();
            try
            {
                if (param == null)
                {
                    return new RespRet<object>(false, "请传递参数");
                }
                if (string.IsNullOrWhiteSpace(param.code))
                {
                    param.code = "110000";
                }
                param.code = param.code.Replace("000", "");
                string zsql = @" select (select (round(zccount*1.00*100/zcount,2)) zcl from (select count(1) zcount,(select count(1) zccount from zm_pc_yh where create_on BETWEEN @startime and @endtime and fwbh not in (select fwbh From zm_pc_base_cj where fwzt is not null) and fwbh not in (select fwbh From zm_pc_base_sqjz where fwzt is not null and yhly='4')
) from zm_buildings) tt),zcount,ydb,wdb,dbl dbl from  rysstd_gq_text('','','2024-01-01',now()::timestamp,'zm_pc_base')  ";
                var data = _dbContext.Database.GetDbConnection().Query<object>(zsql, new { @startime = param.startime, @endtime = param.endtime }).ToList();
                var res = new RespRet<object>(true, "Ok", data);
                return res;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString(), ex.ToString());
                WriteSystemLog(usernNumber, "houses/GetZcData", res);
                res.Msg = "系统异常";
                return res;
            }
        }

        [AllowAnonymous]
        [HttpGet("houses/GetToken")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<AuthenticateResponse> GetToken()
        {
            string userNumber = Guid.NewGuid().ToString();

            var cached = _userService.GetRefreshTokens(userNumber);

            // authentication successful so generate jwt and refresh tokens
            var jwtToken = GenerateJwtToken(userNumber);
            var refreshToken = GenerateRefreshToken(userNumber, null);

            // save refresh token
            if (cached.Succ)
            {
                cached.Data.Tokens.Add(jwtToken.Sha256(), jwtToken);
                cached.Data.RefreshTokens.Add(refreshToken.Token.Sha256(), refreshToken);
                _userService.UpdateRefreshTokens(cached.Data);
            }
            else
            {
                var userRefreshToken = new UserRefreshToken(userNumber);
                userRefreshToken.Tokens.Add(jwtToken.Sha256(), jwtToken);
                userRefreshToken.RefreshTokens.Add(refreshToken.Token.Sha256(), refreshToken);
                _userService.UpdateRefreshTokens(userRefreshToken);
            }

            return new RespRet<AuthenticateResponse>(true, "Ok"
                , new AuthenticateResponse(userNumber, jwtToken, refreshToken.Token, null));
        }


        private string GenerateJwtToken(string userNumber)
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var claims = new[]
            {
                new Claim(ClaimTypes.Sid,userNumber)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenManagement.Secret));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var jwtToken = new JwtSecurityToken(_tokenManagement.Issuer
                , _tokenManagement.Audience
                , claims
                , expires: DateTime.Now.AddMinutes(_tokenManagement.AccessExpiration)
                , signingCredentials: credentials);

            return tokenHandler.WriteToken(jwtToken);
        }

        private RefreshToken GenerateRefreshToken(string userNumber, string ipAddress)
        {
            using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                var randomBytes = new byte[64];
                rngCryptoServiceProvider.GetBytes(randomBytes);
                var chars = $"{userNumber}.{UrlBase64.Encode(randomBytes, PaddingPolicy.Discard)}";
                return new RefreshToken
                {
                    Token = chars,
                    Expires = DateTime.Now.AddMinutes(_tokenManagement.RefreshExpiration),
                    Created = DateTime.Now,
                    CreatedByIp = ipAddress
                };
            }
        }


        public class Baselog
        {
            public string fwbh { get; set; }

            public string id { get; set; }
            public DateTime create_on { get; set; }

            public string fwzt { get; set; }
        }

        /// <summary>
        /// 防火委平台接口  接口中提供自建房总数、周自查率、人员疏散通道已达标数、未达标数、达标率
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("houses/AllCount")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> AllCount()
        {
            string insertsql = " insert into fw_status (id,fwbh,fwzt,create_on) values ((select uuid_generate_v4()),@fwbh,@fwzt,@create_on) ";
            string sql = " select distinct fwbh from ( select distinct fwbh from zm_pc_baselog_cj where xzqdm!='110105' union all select distinct fwbh from  zm_pc_baselog_sqjz where xzqdm!='110105' and yhly='4') a where fwbh not in (select distinct fwbh from fw_status) ";
            var data = _dbContext.Database.GetDbConnection().Query<string>(sql, null).ToList();
            foreach (var item in data)
            {
                int i = 0;
                string cjsql = " select id,fwbh,create_on,fwzt From zm_pc_baselog_cj  where fwbh=@fwbh  order by create_on  ";
                var cjdata = _dbContext.Database.GetDbConnection().Query<Baselog>(cjsql, new { @fwbh = item }).ToList();
                //村级
                if (cjdata != null && cjdata.Count > 0)
                {
                    foreach (var cj in cjdata)
                    {
                        var bigdata = cjdata.Where(c => c.create_on.Date == cj.create_on.Date && c.create_on > cj.create_on).FirstOrDefault();
                        if (bigdata != null)
                        {
                            continue;
                        }
                        string jzsql1 = " select id,fwbh,create_on,fwzt From zm_pc_baselog_sqjz  where fwbh=@fwbh  and yhly='4' and  date(create_on) <=@date order by create_on desc ";
                        var jzdata1 = _dbContext.Database.GetDbConnection().Query<Baselog>(jzsql1, new { @fwbh = item, @date = cj.create_on }).FirstOrDefault();
                        if (jzdata1 != null)
                        {
                            if (cj.fwbh != null)
                            {
                                var resdata = _dbContext.Database.GetDbConnection().Execute(insertsql, new { @id = Guid.NewGuid().ToString(), @fwbh = cj.fwbh, @fwzt = cj.fwzt, @create_on = cj.create_on });
                            }
                            else if (jzdata1.fwbh != null)
                            {
                                var resdata = _dbContext.Database.GetDbConnection().Execute(insertsql, new { @id = Guid.NewGuid().ToString(), @fwbh = jzdata1.fwbh, @fwzt = jzdata1.fwzt, @create_on = jzdata1.create_on });
                            }
                            else
                            {
                                var resdata = _dbContext.Database.GetDbConnection().Execute(insertsql, new { @id = Guid.NewGuid().ToString(), @fwbh = cj.fwbh, @fwzt = cj.fwzt, @create_on = cj.create_on });
                            }
                        }
                        else
                        {
                            var resdata = _dbContext.Database.GetDbConnection().Execute(insertsql, new { @id = Guid.NewGuid().ToString(), @fwbh = cj.fwbh, @fwzt = cj.fwzt, @create_on = cj.create_on });
                        }
                    }
                }
                //街镇
                string jzsql = " select id,fwbh,create_on,fwzt From zm_pc_baselog_sqjz  where fwbh=@fwbh  and yhly='4'  order by create_on  ";
                var jzdata = _dbContext.Database.GetDbConnection().Query<Baselog>(jzsql, new { @fwbh = item }).ToList();
                if (jzdata != null && jzdata.Count > 0)
                {
                    foreach (var jz in jzdata)
                    {
                        var bigdata = jzdata.Where(c => c.create_on.Date == jz.create_on.Date && c.create_on > jz.create_on).FirstOrDefault();
                        if (bigdata != null)
                        {
                            continue;
                        }
                        string distinctsql = " select *from  zm_pc_baselog_cj where fwbh=@fwbh and date(create_on)=@date ";

                        var distinctdata = _dbContext.Database.GetDbConnection().Query<Baselog>(distinctsql, new { @fwbh = item, @date = jz.create_on }).FirstOrDefault();
                        if (distinctdata != null)
                        {
                            continue;
                        }
                        string cjsql1 = " select id,fwbh,create_on,fwzt From zm_pc_baselog_cj  where fwbh=@fwbh  and  date(create_on) <=@date order by create_on desc ";
                        var cjdata1 = _dbContext.Database.GetDbConnection().Query<Baselog>(cjsql1, new { @fwbh = item, @date = jz.create_on }).FirstOrDefault();
                        if (cjdata1 != null)
                        {
                            if (jz.fwbh != null)
                            {
                                var resdata = _dbContext.Database.GetDbConnection().Execute(insertsql, new { @id = Guid.NewGuid().ToString(), @fwbh = jz.fwbh, @fwzt = jz.fwzt, @create_on = jz.create_on });
                            }
                            else if (cjdata1.fwbh != null)
                            {
                                var resdata = _dbContext.Database.GetDbConnection().Execute(insertsql, new { @id = Guid.NewGuid().ToString(), @fwbh = cjdata1.fwbh, @fwzt = cjdata1.fwzt, @create_on = cjdata1.create_on });
                            }
                            else
                            {
                                var resdata = _dbContext.Database.GetDbConnection().Execute(insertsql, new { @id = Guid.NewGuid().ToString(), @fwbh = jz.fwbh, @fwzt = jz.fwzt, @create_on = jz.create_on });
                            }
                        }
                        else
                        {
                            var resdata = _dbContext.Database.GetDbConnection().Execute(insertsql, new { @id = Guid.NewGuid().ToString(), @fwbh = jz.fwbh, @fwzt = jz.fwzt, @create_on = jz.create_on });
                        }
                    }
                }
                i++;
                Console.WriteLine(i);
            }
            return null;
        }





        public class Page<T>
        {
            public Page()
            {

            }
            public Page(List<T> items, int pageIndex, int pageSize, int totalCount)
            {
                NextPageIndex = pageIndex;
                PageSize = pageSize;
                Total = totalCount;
                PageTotal = (int)Math.Ceiling(totalCount / (double)pageSize);
                Items = items;
            }

            /// <summary>
            /// 下一页页码
            /// </summary>
            public int NextPageIndex { get; set; }

            /// <summary>
            /// 每页记录数
            /// </summary>
            public int PageSize { get; set; }

            /// <summary>
            /// 总记录数
            /// </summary>
            public int Total { get; set; }

            /// <summary>
            /// 总页数
            /// </summary>
            public int PageTotal { get; set; }

            /// <summary>
            /// 分页数据
            /// </summary>
            public List<T> Items { get; set; }
        }

        public class PagePc<T>
        {
            public PagePc()
            {

            }
            public PagePc(List<T> items, int pageIndex, int pageSize, int totalCount)
            {
                NextPageIndex = pageIndex;
                PageSize = pageSize;
                Total = totalCount;
                PageTotal = (int)Math.Ceiling(totalCount / (double)pageSize);
                Items = items;
                //Yzc = yzc;
                //Wzc = wzc;
                //Yjc = yjc;
                //Wjc = wjc;
                //Yccbcz = yccbcz;
            }

            /// <summary>
            /// 下一页页码
            /// </summary>
            public int NextPageIndex { get; set; }

            /// <summary>
            /// 每页记录数
            /// </summary>
            public int PageSize { get; set; }

            /// <summary>
            /// 总记录数
            /// </summary>
            public int Total { get; set; }

            /// <summary>
            /// 总页数
            /// </summary>
            public int PageTotal { get; set; }

            /// <summary>
            /// 分页数据
            /// </summary>
            public List<T> Items { get; set; }

            //public int Yzc { get; set; }
            //public int Wzc { get; set; }
            //public int Yjc { get; set; }
            //public int Wjc { get; set; }

            //public int Yccbcz { get; set; }
        }



        /// <summary>
        /// 房屋列表
        /// </summary>
        public class FwlbPc
        {


            /// <summary>
            /// 排序字段（0-房屋编号;1-房屋地址；2-自查状态；3检查状态）
            /// </summary>
            public int OrderBy { get; set; } = 0;

            /// <summary>
            /// 是否降序排序
            /// </summary>
            public bool OrderDesc { get; set; } = false;

            public string text { get; set; }

            public string fwbh { get; set; }

            public string address { get; set; }

            public string hzxm { get; set; }

            /// <summary>
            /// 层数   1一层2二层  3大于二层
            /// </summary>
            public int cs { get; set; }
            /// <summary>
            /// 建设人员疏散通道是否达标   1是  0否
            /// </summary>
            public int isdb { get; set; } = -1;

            /// <summary>
            /// 页码从0开始
            /// </summary>
            public int? pczt { get; set; }

            public int? zczt { get; set; }

            public int? ispc { get; set; }//是否检查   1是0否

            public int? iszc { get; set; }//是否自查 1是0否

            public int fwzt { get; set; } = 0;

            public string Towndm { get; set; }

            public string Xzqdm { get; set; }
            public string Villagedm { get; set; }
            /// <summary>
            /// 页码从0开始
            /// </summary>
            public int PageIndex { get; set; } = 0;

            /// <summary>
            /// 每页个数
            /// </summary>
            public int Limit { get; set; } = 50;

        }


        /// <summary>
        /// 房屋列表
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("houses/search-fwlb")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<FwlbDto>>), 200)]
        public RespRet<PagePc<object>> Fwlb([FromBody] FwlbPc pageRequest)
        {
            if (pageRequest == null)
            {
                return new RespRet<PagePc<object>>(false, "请传递参数");
            }
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<PagePc<object>>(false, "PageIndex must >= 0");
            }
            try
            {


                string time = DateTime.Today
     .AddHours(23)
     .AddMinutes(59)
     .AddSeconds(59)
     .ToString("yyyy-MM-dd HH:mm:ss");

                string table_name = "zm_building_fwzt_" + DateTime.Now.Year;
                var sbSql = new StringBuilder();
                var sbSqlCount = new StringBuilder();
                var yccbczsql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@" 
    
SELECT
 address, 
 hzxm, 
xzqdm,xzq,
 fwbh, 
towndm,town,villagedm,village,
 ST_X(ST_Centroid(ST_Collect(geom))) AS villagelongitude,
 ST_Y(ST_Centroid(ST_Collect(geom))) AS villagelatitude,
 st_asgeojson(geom) AS geometry,
 CASE
        WHEN geom IS NULL THEN NULL
        ELSE json_build_object(
            'type', 'Feature',
            'geometry', json_build_object(
                'type', 'MultiPolygon',
                'coordinates', ST_AsGeoJSON(geom)::json->'coordinates'
            ),
            'properties', json_build_object(
                'fwbh',fwbh,
                'address',address, 
                'hzxm',hzxm,
                'xzqdm',xzqdm,
                'xzq',xzq
            )
        )
    END AS feature
FROM zm_buildings where 1=1   ");
                sbSqlCount.Append($@" SELECT
 count(1) count	
FROM  zm_buildings where 1=1 and fwbh  not in  (select fwbh From  {table_name} where final_create_on=@time  and final_fwzt is not null  ) ");

                //if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                //{
                //    CountSql.Append($@" and b.villagedm=@villagedm ");
                //    sbSql.Append($@" and b.villagedm=@villagedm ");
                //    sbSqlCount.Append($@" and b.villagedm=@villagedm ");
                //    yccbczsql.Append($@" and b.villagedm=@villagedm ");
                //    sqlParams.Add(new NpgsqlParameter("villagedm", $"{pageRequest.Villagedm}"));
                //}
                //if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                //{
                //    CountSql.Append($@" and b.towndm=@towndm ");
                //    sbSql.Append($@" and b.towndm=@towndm ");
                //    sbSqlCount.Append($@" and b.towndm=@towndm ");
                //    yccbczsql.Append($@" and b.towndm=@towndm ");
                //    sqlParams.Add(new NpgsqlParameter("towndm", $"{pageRequest.Towndm}"));
                //}
                //if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                //{
                //    CountSql.Append($@" and b.xzqdm=@xzqdm ");
                //    sbSql.Append($@" and b.xzqdm=@xzqdm ");
                //    sbSqlCount.Append($@" and b.xzqdm=@xzqdm ");
                //    yccbczsql.Append($@" and b.xzqdm=@xzqdm ");
                //    sqlParams.Add(new NpgsqlParameter("xzqdm", $"{pageRequest.Xzqdm}"));
                //}
                if (!string.IsNullOrWhiteSpace(pageRequest.text))
                {
                    sbSql.Append($@" and ( hzxm like @text or address like @text or fwbh like @text ) ");
                    sbSqlCount.Append($@" and ( hzxm like @text or address like @text or fwbh like @text ) ");
                    sqlParams.Add(new NpgsqlParameter("text", "%" + pageRequest.text + "%"));
                }

                if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                {
                    sbSql.Append($@" and xzqdm=@xzqdm ");
                    sbSqlCount.Append($@" and xzqdm=@xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("xzqdm", "%" + pageRequest.Xzqdm + "%"));
                }
                sqlParams.Add(new NpgsqlParameter("time", time));
                sbSql.Append($@" group by fwbh,address,hzxm,geom,xzqdm,xzq,towndm,town,villagedm,village  ");
                var count = _dbContext.Database.GetDbConnection().Query<int>(sbSqlCount.ToString(), new { @xzqdm = pageRequest.Xzqdm, @time = time, text = "%" + pageRequest.text + "%" }).FirstOrDefault();
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));
                var datas = _dbContext.Database.GetDbConnection().Query<object>(sbSql.ToString(), new { @xzqdm = pageRequest.Xzqdm, @text = "%" + pageRequest.text + "%", @limit = pageRequest.Limit, @offset = pageRequest.Limit * (pageRequest.PageIndex - 1) }).ToList();
                //var datas = _dbContext.FwlbDto.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).Select(_ => _mapper.Map<FwlbDto>(_)).ToList();
                var pageData = new PagePc<object>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                var r = new RespRet<PagePc<object>>(true, "Ok", pageData);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<PagePc<object>>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }

        /// <summary>
        /// 动态矢量瓦片服务(查询数据)
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("houses/mapbox/vector/tiles_q")]
        public ActionResult GetVectorTile_Q([FromQuery] int z, [FromQuery] int x, [FromQuery] int y)
        {
            string strand = "";
            var sql = $@" SELECT
            ST_AsMVT(P, 'ffpolygon', 4096, 'geom') AS tile
            FROM
            (SELECT
            ST_AsMVTGeom( ST_Transform(ST_SetSRID(geom, 4326), 3857), ST_TileEnvelope( {z}, {x}, {y}),4096,256,FALSE) AS geom,fwbh,address,hzxm,xzqdm,xzq, ST_X(ST_Centroid(ST_Collect(geom))) AS villagelongitude,
 ST_Y(ST_Centroid(ST_Collect(geom))) AS villagelatitude
            FROM zm_buildings
            WHERE ST_Intersects(ST_SetSRID(geom, 4326), ST_Transform(ST_TileEnvelope({z}, {x}, {y}), 4326)) 
        AND geom IS NOT NULL
        AND NOT ST_IsEmpty(geom)
        AND ST_IsValid(ST_MakeValid(geom))  GROUP BY geom,fwbh,address,hzxm,xzqdm,xzq ) AS P ";
            // var tile = _dbContext.Database.GetDbConnection().Query<byte[]>(sql).FirstOrDefault();
            // string SqlTask_d = @"UPDATE re_task set ower_unit_id = '" + getdata.ref_id + "' WHERE task_id = '" + getdata.task_id + "';";
            var tile = (byte[])_dbContext.Database.GetDbConnection().ExecuteScalar(sql, null);
            return File(tile, "application/vnd.mapbox-vector-tile");
        }




        /// <summary>
        /// 自查记录
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("houses/search-attryhzclog")]
        [Produces("application/json")]
        public RespRet<Page<object>> attrzclog([FromBody] PageHouseRequestInputCj pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<object>>(false, "PageIndex must >= 0");
            }
            var userNumber = this.CurrentUser();
            var user = _dbContext.ZmUser.FirstOrDefault(u => u.Number == userNumber && u.IsDelete != 1 && u.Disabled != 1);
            try
            {
                var sbSql = new StringBuilder();
                var sbSqlcount = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sbSqlWhere2 = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                {
                    sbSqlWhere.Append($@" and a.villagedm like @villagedm ");
                    sqlParams.Add(new NpgsqlParameter("villagedm", $"{"%" + pageRequest.Villagedm + "%"}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                {
                    sbSqlWhere.Append($@" and a.Towndm like @Towndm ");
                    sqlParams.Add(new NpgsqlParameter("Towndm", $"{"%" + pageRequest.Towndm + "%"}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                {
                    sbSqlWhere.Append($@" and a.Xzqdm like @Xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("Xzqdm", $"{"%" + pageRequest.Xzqdm + "%"}"));
                }
                if (pageRequest.Pczt >= 1)
                {
                    sbSqlWhere.Append($@" and a.pczt =@pczt ");
                    sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.Pczt));
                }
                if (pageRequest.Yhly == 1)
                {
                    sbSqlWhere2.Append($@" and yhly='自查' ");
                }
                if (pageRequest.Yhly == 2)
                {
                    sbSqlWhere2.Append($@" and yhly!='自查' ");
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Text))
                {
                    sbSqlWhere.Append($@" and (b.fwbh like @text or b.hzxm like @text or b.address like @text) ");
                    sqlParams.Add(new NpgsqlParameter("text", $"{"%" + pageRequest.Text + "%"}"));
                }
                if (pageRequest.CheckTime != null)
                {
                    if (pageRequest.CheckTime.Count == 2)
                    {
                        sbSqlWhere.Append($@" and date(create_on) between @start and @end  ");
                        sqlParams.Add(new NpgsqlParameter("start", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("end", pageRequest.CheckTime[1]));
                    }
                }
                sbSql.Append($@" select *from ( SELECT (select nickname create_name from zm_user_cj where number=a.create_by), b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by,TO_CHAR(a.create_on, 'YYYY-MM-DD HH24:MI:SS') create_on,TO_CHAR(a.pcsj, 'YYYY-MM-DD HH24:MI:SS') pcsj, a.jczt,case when a.jcly='5' then '村级检查' when a.jcly='4' then '街镇核查' when a.jcly='3' then '区级核查' when a.jcly='2' then '市级核查' end yhly
        FROM zm_pc_yhlog_sqjz a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 and  base_id in (select id from zm_pc_baselog_sqjz where id=base_id  )and 1=1   {sbSqlWhere} 
         union all
        SELECT (select nickname create_name from zm_user_cj where number=a.create_by),b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, TO_CHAR(a.create_on, 'YYYY-MM-DD HH24:MI:SS') create_on,TO_CHAR(a.pcsj, 'YYYY-MM-DD HH24:MI:SS') pcsj, a.jczt,'自查'yhly
        FROM zm_pc_yhlog a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 {sbSqlWhere}   )a  where 1=1 {sbSqlWhere2} ");

                sbSqlcount.Append($@" select count(1) from ( SELECT (select nickname create_name from zm_user_cj where number=a.create_by), b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, a.create_on, a.pcsj,a.jczt,'核查' yhly
        FROM zm_pc_yhlog_sqjz a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 and  base_id in (select id from zm_pc_baselog_sqjz where id=base_id  )and 1=1   {sbSqlWhere} 
         union all
        SELECT (select nickname create_name from zm_user_cj where number=a.create_by),b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, a.create_on, a.pcsj, a.jczt,'自查'yhly
        FROM zm_pc_yhlog a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 {sbSqlWhere}   )a  where 1=1 {sbSqlWhere2} ");
                var count = _dbContext.Database.GetDbConnection().Query<int>(sbSqlcount.ToString(), new { @text = pageRequest.Text }).FirstOrDefault();
                sbSql.Append($@" order by create_on desc");
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));

                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));
                var datas = _dbContext.Database.GetDbConnection().Query<object>(sbSql.ToString(), new { @text = pageRequest.Text, @limit = pageRequest.Limit, @offset = pageRequest.Limit * (pageRequest.PageIndex - 1) }).ToList();
                var pageData = new Page<object>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);
                var r = new RespRet<Page<object>>(true, "Ok", pageData);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<Page<object>>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 根据自查、核查记录详情
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("houses/search-zchcyhlogdetaileall")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> YhlogdetaileAll([FromQuery] string id)
        {
            // var userNumber = this.CurrentUser();
            try
            {
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@"select *  FROM zm_pc_yhlog_sqjz    ");
                sbSqlWhere.Append($@" id = @fwbh and base_id in (select id from zm_pc_baselog_sqjz where id=base_id )and");
                sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));
                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                var from = _dbContext.ZmPcYhLogSqjz.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (from == null)
                {
                    sbSql = new StringBuilder();
                    sbSqlWhere = new StringBuilder();
                    sqlParams = new List<NpgsqlParameter>();

                    sbSql.Append($@"select *  FROM zm_pc_yhlog    ");

                    sbSqlWhere.Append($@" id = @fwbh and");
                    sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));

                    if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                    {
                        sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                    }
                    var yhlog = _dbContext.ZmPcYhLog.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                    if (yhlog == null)
                    {
                        var res = new RespRet<object>(false, "未找到记录", yhlog);
                        return res;
                    }
                    yhlog.UseElectricBicyclePhoto = yhlog.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseElectricBicyclePhoto));
                    yhlog.UseBottledLiquefiedGasPhoto = yhlog.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseBottledLiquefiedGasPhoto));
                    yhlog.UseStackedItemsPhoto = yhlog.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseStackedItemsPhoto));
                    yhlog.SlljdxPhoto = yhlog.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.SlljdxPhoto));
                    yhlog.YgbjwfwhyxPhoto = yhlog.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.YgbjwfwhyxPhoto));
                    yhlog.MhqwbcwhyxPhoto = yhlog.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.MhqwbcwhyxPhoto));
                    yhlog.JyplmhxtwbcwhyxPhoto = yhlog.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.JyplmhxtwbcwhyxPhoto));
                    yhlog.UseElectricBicycleZgPhoto = yhlog.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseElectricBicycleZgPhoto));
                    yhlog.UseBottledLiquefiedGasZgPhoto = yhlog.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseBottledLiquefiedGasZgPhoto));
                    yhlog.UseStackedItemsZgPhoto = yhlog.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseStackedItemsZgPhoto));
                    yhlog.SlljdxZgPhoto = yhlog.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.SlljdxZgPhoto));
                    yhlog.YgbjwfwhyxMsgZgPhoto = yhlog.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.YgbjwfwhyxMsgZgPhoto));
                    yhlog.MhqwbcwhyxZgPhoto = yhlog.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.MhqwbcwhyxZgPhoto));
                    yhlog.JyplmhxtwbcwhyxZgPhoto = yhlog.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.JyplmhxtwbcwhyxZgPhoto));
                    //返回采集信息
                    var ZmPcBase = _dbContext.ZmPcBaseLog.FirstOrDefault(u => u.Id == yhlog.BaseId && u.IsDelete != 1);
                    var ZmPcBaseDto1 = _mapper.Map<ZmPcBaseLogCjDto>(ZmPcBase);
                    var ZmPcYhDto1 = _mapper.Map<ZmPcYhLogCjDto2>(yhlog);
                    var re = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBaseDto1, ZmPcYh = ZmPcYhDto1 });
                    return re;
                }
                from.UseElectricBicyclePhoto = from.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicyclePhoto));
                from.UseBottledLiquefiedGasPhoto = from.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasPhoto));
                from.UseStackedItemsPhoto = from.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsPhoto));
                from.SlljdxPhoto = from.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxPhoto));

                from.YgbjwfwhyxPhoto = from.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxPhoto));
                from.MhqwbcwhyxPhoto = from.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxPhoto));
                from.JyplmhxtwbcwhyxPhoto = from.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxPhoto));
                from.UseElectricBicycleZgPhoto = from.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicycleZgPhoto));
                from.UseBottledLiquefiedGasZgPhoto = from.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasZgPhoto));
                from.UseStackedItemsZgPhoto = from.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsZgPhoto));
                from.SlljdxZgPhoto = from.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxZgPhoto));
                from.YgbjwfwhyxMsgZgPhoto = from.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxMsgZgPhoto));
                from.MhqwbcwhyxZgPhoto = from.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxZgPhoto));
                from.JyplmhxtwbcwhyxZgPhoto = from.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxZgPhoto));
                //返回采集信息
                var ZmPcBasecj = _dbContext.ZmPcBaseLogSqjz.FirstOrDefault(u => u.Id == from.BaseId && u.IsDelete != 1);
                var ZmPcBaseDto = _mapper.Map<ZmPcBaseLogCjDto>(ZmPcBasecj);
                var ZmPcYhDto = _mapper.Map<ZmPcYhLogCjDto2>(from);
                var r = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBaseDto, ZmPcYh = ZmPcYhDto });
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }
        private List<string> JsonStr2List(string jsonStr)
        {
            try
            {
                return JsonConvert.DeserializeObject<List<string>>(jsonStr);
            }
            catch (System.Exception)
            {
            }

            return null;
        }


        /// <summary>
        /// 获取隐患记录详情
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("houses/search-yhlogdetaileall")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<object> yhlogdetaileall([FromQuery] string id)
        {
            // var userNumber = this.CurrentUser();
            try
            {
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();

                sbSql.Append($@"select *  FROM zm_pc_yhlog_cj    ");

                sbSqlWhere.Append($@" id = @fwbh and");
                sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));

                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                var from = _dbContext.ZmPcYhLogCj.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (from == null)
                {
                    sbSql = new StringBuilder();
                    sbSqlWhere = new StringBuilder();
                    sqlParams = new List<NpgsqlParameter>();
                    sbSql.Append($@"select *  FROM zm_pc_yhlog    ");
                    sbSqlWhere.Append($@" id = @fwbh and");
                    sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));
                    if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                    {
                        sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                    }
                    var yhlog = _dbContext.ZmPcYhLog.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();

                    if (yhlog == null)
                    {
                        var res = new RespRet<object>(false, "未找到自查记录", yhlog);
                        return res;
                    }
                    yhlog.UseElectricBicyclePhoto = yhlog.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseElectricBicyclePhoto));
                    yhlog.UseBottledLiquefiedGasPhoto = yhlog.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseBottledLiquefiedGasPhoto));
                    yhlog.UseStackedItemsPhoto = yhlog.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseStackedItemsPhoto));
                    yhlog.SlljdxPhoto = yhlog.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.SlljdxPhoto));
                    yhlog.YgbjwfwhyxPhoto = yhlog.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.YgbjwfwhyxPhoto));
                    yhlog.MhqwbcwhyxPhoto = yhlog.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.MhqwbcwhyxPhoto));
                    yhlog.JyplmhxtwbcwhyxPhoto = yhlog.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.JyplmhxtwbcwhyxPhoto));
                    yhlog.UseElectricBicycleZgPhoto = yhlog.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseElectricBicycleZgPhoto));
                    yhlog.UseBottledLiquefiedGasZgPhoto = yhlog.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseBottledLiquefiedGasZgPhoto));
                    yhlog.UseStackedItemsZgPhoto = yhlog.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.UseStackedItemsZgPhoto));
                    yhlog.SlljdxZgPhoto = yhlog.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.SlljdxZgPhoto));
                    yhlog.YgbjwfwhyxMsgZgPhoto = yhlog.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.YgbjwfwhyxMsgZgPhoto));
                    yhlog.MhqwbcwhyxZgPhoto = yhlog.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.MhqwbcwhyxZgPhoto));
                    yhlog.JyplmhxtwbcwhyxZgPhoto = yhlog.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(yhlog.JyplmhxtwbcwhyxZgPhoto));
                    //返回采集信息
                    var ZmPcBase = _dbContext.ZmPcBaseLog.FirstOrDefault(u => u.Id == yhlog.BaseId && u.IsDelete != 1);

                    var re = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBase, ZmPcYh = yhlog });
                    return re;
                }
                from.UseElectricBicyclePhoto = from.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicyclePhoto));
                from.UseBottledLiquefiedGasPhoto = from.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasPhoto));
                from.UseStackedItemsPhoto = from.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsPhoto));
                from.SlljdxPhoto = from.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxPhoto));


                from.YgbjwfwhyxPhoto = from.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxPhoto));
                from.MhqwbcwhyxPhoto = from.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxPhoto));
                from.JyplmhxtwbcwhyxPhoto = from.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxPhoto));
                from.UseElectricBicycleZgPhoto = from.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicycleZgPhoto));
                from.UseBottledLiquefiedGasZgPhoto = from.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasZgPhoto));
                from.UseStackedItemsZgPhoto = from.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsZgPhoto));
                from.SlljdxZgPhoto = from.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxZgPhoto));
                from.YgbjwfwhyxMsgZgPhoto = from.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxMsgZgPhoto));
                from.MhqwbcwhyxZgPhoto = from.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxZgPhoto));
                from.JyplmhxtwbcwhyxZgPhoto = from.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxZgPhoto));
                //返回采集信息
                var ZmPcBasecj = _dbContext.ZmPcBaseLogCj.FirstOrDefault(u => u.Id == from.BaseId && u.IsDelete != 1);

                var r = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBasecj, ZmPcYh = from });
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }




        /// <summary>
        /// 自查记录、检查记录
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("houses/search-yhlog")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<Page<object>>), 200)]
        public RespRet<Page<object>> attrzcjclog([FromBody] PageHouseRequestInputCj pageRequest)
        {
            if (pageRequest.PageIndex < 0)
            {
                return new RespRet<Page<object>>(false, "PageIndex must >= 0");
            }
            try
            {
                pageRequest.Pczt = 2;
                var sbSql = new StringBuilder();
                var sbSqlcount = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sbSqlWhere2 = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                if (!string.IsNullOrWhiteSpace(pageRequest.Villagedm))
                {
                    sbSqlWhere.Append($@" and a.villagedm like @villagedm ");
                    sqlParams.Add(new NpgsqlParameter("villagedm", $"{"%" + pageRequest.Villagedm + "%"}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Towndm))
                {
                    sbSqlWhere.Append($@" and a.Towndm like @Towndm ");
                    sqlParams.Add(new NpgsqlParameter("Towndm", $"{"%" + pageRequest.Towndm + "%"}"));
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Xzqdm))
                {
                    sbSqlWhere.Append($@" and a.Xzqdm like @Xzqdm ");
                    sqlParams.Add(new NpgsqlParameter("Xzqdm", $"{"%" + pageRequest.Xzqdm + "%"}"));
                }
                if (pageRequest.Pczt >= 1)
                {
                    sbSqlWhere.Append($@" and a.pczt =@pczt ");
                    sqlParams.Add(new NpgsqlParameter("pczt", pageRequest.Pczt));
                }
                if (pageRequest.Yhly == 1)
                {
                    sbSqlWhere2.Append($@" and yhly='自查' ");
                }
                if (pageRequest.Yhly == 2)
                {
                    sbSqlWhere2.Append($@" and yhly='检查' ");
                }
                if (!string.IsNullOrWhiteSpace(pageRequest.Text))
                {
                    sbSqlWhere.Append($@" and (b.fwbh like @text or b.hzxm like @text or b.address like @text) ");
                    sqlParams.Add(new NpgsqlParameter("text", $"{"%" + pageRequest.Text + "%"}"));
                }
                if (pageRequest.CheckTime != null)
                {
                    if (pageRequest.CheckTime.Count == 2)
                    {
                        sbSqlWhere.Append($@" and date(create_on) between @start and @end  ");
                        sqlParams.Add(new NpgsqlParameter("start", pageRequest.CheckTime[0]));
                        sqlParams.Add(new NpgsqlParameter("end", pageRequest.CheckTime[1]));
                    }
                }
                sbSql.Append($@" select *from ( SELECT (select nickname create_name from zm_user_cj where number=a.create_by),b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, a.create_on, a.pcsj, a.jczt,'检查' yhly
        FROM zm_pc_yhlog_cj a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 {sbSqlWhere} 
         union all
        SELECT (select nickname create_name from zm_user_cj where number=a.create_by),b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, a.create_on, a.pcsj, a.jczt,'自查'yhly
        FROM zm_pc_yhlog a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 {sbSqlWhere}   )a  where 1=1 {sbSqlWhere2} ");
                sbSqlcount.Append($@" select count(1) from ( SELECT (select nickname create_name from zm_user_cj where number=a.create_by),b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, a.create_on, a.pcsj, a.jczt,'检查' yhly
        FROM zm_pc_yhlog_cj a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 {sbSqlWhere} 
         union all
        SELECT (select nickname create_name from zm_user_cj where number=a.create_by),b.hzxm, b.address, a.id, a.fwbh, a.pczt, a.create_by, a.create_on, a.pcsj, a.jczt,'自查'yhly
        FROM zm_pc_yhlog a
        JOIN zm_buildings b ON a.fwbh = b.fwbh where 1=1 {sbSqlWhere}   )a  where 1=1 {sbSqlWhere2} ");
                var count = _dbContext.Database.GetDbConnection().Query<int>(sbSqlcount.ToString(), new { @text = pageRequest.Text, @pczt = pageRequest.Pczt }).FirstOrDefault();
                sbSql.Append($@" order by create_on desc");
                sbSql.Append($@" limit @limit offset @offset");
                sqlParams.Add(new NpgsqlParameter("limit", pageRequest.Limit));
                sqlParams.Add(new NpgsqlParameter("offset", pageRequest.Limit * pageRequest.PageIndex));

                var datas = _dbContext.Database.GetDbConnection().Query<object>(sbSql.ToString(), new { @pczt = pageRequest.Pczt, @text = pageRequest.Text, @limit = pageRequest.Limit, @offset = pageRequest.Limit * (pageRequest.PageIndex - 1) }).ToList();
                var pageData = new Page<object>(datas
                    , pageRequest.PageIndex + 1, pageRequest.Limit, count);

                var r = new RespRet<Page<object>>(true, "Ok", pageData);
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<Page<object>>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }





        /// <summary>
        /// 某栋房屋的核查、核查记录
        /// </summary>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("nologin/hc/baseInfo/baseInfoDetaile")]
        [ProducesResponseType(typeof(RespRet<object>), 200)]
        public RespRet<Page<object>> baseInfoDetaile([FromQuery] string fwbh, [FromQuery] string jcly, [FromQuery] int pageIndex, [FromQuery] int limit)
        {
            if (pageIndex < 0)
            {
                return new RespRet<Page<object>>(false, "PageIndex must >= 0");
            }
            if (string.IsNullOrEmpty(jcly))
            {
                jcly = "4";
            }
            string strWhere = "";
            string sql = @"select  ROW_NUMBER() OVER ()index ,*   from ( select b1.*,COALESCE(yhnum,0) yhnum,case when yhnum is null then '已核查无隐患' else  '已核查有隐患' end yhzt,COALESCE(zgnum,0) zgnum,case when fwzt is null then '正常出租' else case when fwzt=1 then '不出租' else  '已拆除' end end fwztname,
                         case when zgnum is null then '/' else case when zgnum=0 then '未整改' else  '已整改' end end zgzt,'详情' cz  from (select t2.hzxm,t2.address,t1.fwbh,t1.id,to_char(t1.create_on::timestamp(0) without time zone, 'YYYY-MM-DD HH24:MI:SS') pcsj ,yhly,create_name  ,fwzt
                           from zm_pc_baselog_sqjz t1,zm_buildings t2 where t1.fwbh=t2.fwbh and t1.yhly='" + jcly + "' ) b1 left join " +
                          " (select count(fwbh) yhnum, yhlog_id, sum(case when zg_value= '1' then 1 else 0 end) zgnum from zm_pc_yhlog_dx_sqjz  " +
                          " group by yhlog_id) b2 on b1.id = b2.yhlog_id  order by pcsj desc)  t    " +
                      " where fwbh='" + fwbh + "' " + strWhere + "   limit " + limit + " offset " + limit * (pageIndex - 1);
            if (sql.Contains("insert into", StringComparison.OrdinalIgnoreCase)
         || sql.Contains("delete from", StringComparison.OrdinalIgnoreCase)
         || sql.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<Page<object>>(false, "不符合规范，禁止执行");
            }
            string sql_count = @"select  count(1) cnt  from ( select b1.*,COALESCE(yhnum,0) yhnum,case when yhnum is null then '已核查无隐患' else  '已核查有隐患' end yhzt,COALESCE(zgnum,0) zgnum, case when fwzt is null then '正常出租' else case when fwzt=1 then '不出租' else  '已拆除' end end fwztname,
                         case when zgnum is null then '/' else case when zgnum=0 then '未整改' else  '已整改' end end zgzt,'详情' cz  from (select t2.hzxm,t2.address,t1.fwbh,t1.id,to_char(t1.create_on::timestamp(0) without time zone, 'YYYY-MM-DD HH24:MI:SS') pcsj  ,yhly,create_name,fwzt
                           from zm_pc_baselog_sqjz t1,zm_buildings t2 where t1.fwbh=t2.fwbh and t1.yhly='" + jcly + "') b1 left join " +
                         "  (select count(fwbh) yhnum, yhlog_id, sum(case when zg_value= '1' then 1 else 0 end) zgnum from zm_pc_yhlog_dx_sqjz " +
                         "  group by yhlog_id) b2 on b1.id = b2.yhlog_id order by pcsj desc)  t    where fwbh='" + fwbh + "'" + strWhere;

            if (sql_count.Contains("insert into", StringComparison.OrdinalIgnoreCase)
          || sql_count.Contains("delete from", StringComparison.OrdinalIgnoreCase)
          || sql_count.Contains("update ", StringComparison.OrdinalIgnoreCase))
            {
                return new RespRet<Page<object>>(false, "不符合规范，禁止执行");
            }
            //执行语句
            var list = _dbContext.Database.GetDbConnection().Query<object>(sql).ToList();
            int count = _dbContext.Database.GetDbConnection().QueryFirstOrDefault<int>(sql_count);
            return new RespRet<Page<object>>(true, "ok", new Page<object> { Items = list, NextPageIndex = pageIndex, PageTotal = count, Total = count });
        }


        /// <summary>
        /// 获取当前房屋的核查记录中的详细信息
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("nologin/hc/{id}/restinfo/")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<HourseBaseInfo>), 200)]
        public RespRet<object> restinfo([FromRoute] string id)
        {
            try
            {
                var sbSql = new StringBuilder();
                var sbSqlWhere = new StringBuilder();
                var sqlParams = new List<NpgsqlParameter>();
                sbSql.Append($@"select *  FROM zm_pc_baselog_sqjz    ");
                sbSqlWhere.Append($@" id = @fwbh and");
                sqlParams.Add(new NpgsqlParameter("fwbh", $"{id}"));
                if (!string.IsNullOrEmpty(sbSqlWhere.ToString()))
                {
                    sbSql.Append($@" where {sbSqlWhere} 1=1 ");
                }
                var ZmPcBasecj = _dbContext.ZmPcBaseLogSqjz.FromSqlRaw(sbSql.ToString(), sqlParams.ToArray()).FirstOrDefault();
                if (ZmPcBasecj == null)
                {
                    return new RespRet<object>(false, "未找到核查记录");
                }


                var from = _dbContext.ZmPcYhLogSqjz.FirstOrDefault(c => c.BaseId == id);
                if (from != null)
                {
                    from.UseElectricBicyclePhoto = from.UseElectricBicyclePhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicyclePhoto));
                    from.UseBottledLiquefiedGasPhoto = from.UseBottledLiquefiedGasPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasPhoto));
                    from.UseStackedItemsPhoto = from.UseStackedItemsPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsPhoto));
                    from.SlljdxPhoto = from.SlljdxPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxPhoto));
                    from.YgbjwfwhyxPhoto = from.YgbjwfwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxPhoto));
                    from.MhqwbcwhyxPhoto = from.MhqwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxPhoto));
                    from.JyplmhxtwbcwhyxPhoto = from.JyplmhxtwbcwhyxPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxPhoto));
                    from.UseElectricBicycleZgPhoto = from.UseElectricBicycleZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseElectricBicycleZgPhoto));
                    from.UseBottledLiquefiedGasZgPhoto = from.UseBottledLiquefiedGasZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseBottledLiquefiedGasZgPhoto));
                    from.UseStackedItemsZgPhoto = from.UseStackedItemsZgPhoto == null ? null : string.Join("|", JsonStr2List(from.UseStackedItemsZgPhoto));
                    from.SlljdxZgPhoto = from.SlljdxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.SlljdxZgPhoto));
                    from.YgbjwfwhyxMsgZgPhoto = from.YgbjwfwhyxMsgZgPhoto == null ? null : string.Join("|", JsonStr2List(from.YgbjwfwhyxMsgZgPhoto));
                    from.MhqwbcwhyxZgPhoto = from.MhqwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.MhqwbcwhyxZgPhoto));
                    from.JyplmhxtwbcwhyxZgPhoto = from.JyplmhxtwbcwhyxZgPhoto == null ? null : string.Join("|", JsonStr2List(from.JyplmhxtwbcwhyxZgPhoto));
                }
                var ZmPcBaseDto = _mapper.Map<ZmPcBaseLogCjDto>(ZmPcBasecj);
                var ZmPcYhDto = _mapper.Map<ZmPcYhLogCjDto2>(from);
                var r = new RespRet<object>(true, "Ok", new { ZmPcBase = ZmPcBaseDto, ZmPcYh = ZmPcYhDto });
                return r;
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }


        /// <summary>
        /// 获取当前房屋的核查记录中的详细信息
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="pageRequest"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("house/getjson")]
        [Produces("application/json")]
        [ProducesResponseType(typeof(RespRet<HourseBaseInfo>), 200)]
        public async Task<object> geojson([FromQuery] string code)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync($"https://geo.datav.aliyun.com/areas_v3/bound/{code}.json");
                    response.EnsureSuccessStatusCode(); // 检查响应是否成功
                    string responseBody = await response.Content.ReadAsStringAsync();
                    return  responseBody ;
                }
            }
            catch (Exception ex)
            {
                var res = new RespRet<object>(false, ex.ToString());
                res.Msg = "系统异常";
                return res;
            }
        }
    }
}